# -*- coding: utf-8 -*-
#*******************************************************************************
#   
#   http://www.ikanman.com/comic/\d+/ 解析器                                   
#                                                                                         
#*******************************************************************************
import execjs

from base import *

tag='ikanman'

#---------------------------- 验证模块 ----------------------------

def url_judgement(url):
    if re.match(r'http://www.ikanman.com/comic/\d+/',url):
        return valid_check(url)
    return False

def valid_check(url):
    print('{} catch {}'.format(tag,url))
    content=request_for(url,common_headers);
    if content:
        return get_loader(url)
    return False

def get_loader(url):
    return IkanmanLoader(url,IkanmanPageParser,IkanmanVolParser)

#---------------------------- 下载器 ----------------------------

class IkanmanLoader(ComicLoader):
    def __init__(self,ur,comic_page_parser,comic_vol_parser):
        super().__init__(url,comic_page_parser,comic_vol_parser)

#---------------------------- 解析器 ----------------------------

class IkanmanPageParser(ComicPageParser):
    def __init__(self,comic):
        super().__init__(comic)
        self.max_index=0

    def work(self,content):
        # title
        self.comic.title=re.compile(r'<h1>(.*?)</h1>',re.S|re.M).findall(content)[0]
        # description
        self.comic.description=re.compile(r'</div><div id="intro-all" class="none"><p>(.*?)',re.S|re.M).findall(content)[0].strip()
        # cover
        self.comic.cover=re.compile(r'<p class="hcover"><img src="(.*?)"').findall(content)[0]
        # vols
        urls_content=re.compile(r'<div class="chapter-list cf mt10" id=\'chapter-list-1\'>(.*?)</div>',re.S|re.M).findall(content)
        for urls in urls_content:
            self.feed(urls)

    def handle_starttag(self,tag,attrs):
        if tag=='a':
            infos={}
            for (v,k) in attrs:
                infos[v]=k
            vol=InfoVol('http://www.ikanman.com'+infos['href'],infos['title'].strip())       

class IkanmanVolParser(ComicVolParser):
    def __init__(self):
        super().__init__()

    def work(self,content):
        js=re.compile(r'<script type="text/javascript" src="(.*?)"></script>',re.S).findall(content)[0]
        en_code=re.compile(r'eval\(decryptDES\(\'(.*?)\'\)\)',re.S|re.M).findall(content)[0]
        config_js_content=request_for(js).decode('utf8')
        crypt_content=re.compile(r"jQuery\);(.*?)eval",re.S|re.M|re.X).findall(config_js_content)[0]
        js_dec='''
            function decryptDES(t){
                var decrypted=CryptoJS.DES.decrypt({ciphertext:CryptoJS.enc.Base64.parse(t.substring(8))},CryptoJS.enc.Utf8.parse(t.substring(0,8)),{mode:CryptoJS.mode.ECB,padding:CryptoJS.pad.Pkcs7});
                return decrypted.toString(CryptoJS.enc.Utf8)
            }
        '''
        ctx=execjs.compile(crypt_content+js_dec)
        dec_js_content=ctx.call('decryptDES',en_code)
        eval_content=re.compile(r'eval\((.*)\)',re.S).findall(dec_js_content.strip())[0]
        info=execjs.eval(eval_content)
        pics=re.compile(r'"(.*?)"').findall(re.compile(r':\[(.*?)\]').findall(info)[0])
        path=re.compile(r'path":"(.*?)",').findall(info)[0]
        for pic in pics:
            if pic.endswith('.webp'):
                pic=pic[:-5]
            pic_url="{0}{1}{2}".format('http://i.hamreus.com:8080',urllib.request.quote(path),pic).strip()
            self.pic_urls.append((pic_url,zero_prefix(self.pic_index)))
            self.pic_index+=1
